<template>
  <div class="q-pa-md">
    <q-page>
      <header class="page-header row items-start">
        <q-breadcrumbs class="header-title" active-color="grey-7">
          <q-breadcrumbs-el class="first-breadcrumbs" label="系统管理" />
          <q-breadcrumbs-el label="操作日志" class="text-weight-medium" />
        </q-breadcrumbs>
      </header>

      <!-- 搜索栏 -->
      <div class="q-pa-sm row q-gutter-sm items-center">
        <q-input
          v-model="searchForm.username"
          dense
          outlined
          label="操作人"
          class="col-12 col-sm-4"
        />
        <q-input
          v-model="searchForm.filename"
          dense
          outlined
          label="文件名称"
          class="col-12 col-sm-4"
        />
        <q-select
          v-model="searchForm.operation_type"
          dense
          outlined
          label="操作类型"
          class="col-12 col-sm-4"
          :options="operationOptions"
        />
        <q-btn
          color="primary"
          label="搜索"
          padding="4px 12px"
          @click="loadData"
        />
        <q-btn
          color="primary"
          label="重置"
          padding="4px 12px"
          @click="resetSearch"
          class="q-ml-sm"
        />
      </div>

      <q-table
        :rows="dataList"
        :columns="columns"
        row-key="id"
        :loading="loading"
        virtual-scroll
        :virtual-scroll-sticky-size-start="48"
        table-style="max-height: 700px"
        :pagination="pagination"
        hide-pagination
        @update:pagination="loadData"
      >
        <template v-slot:no-data="{ filter }">
          <div class="full-width row flex-center q-pa-md text-grey">
            <q-icon :name="filter ? 'search_off' : 'sentiment_dissatisfied'" size="2em" class="q-mr-sm" />
            <span>{{ filter ? '未找到匹配的数据' : '暂无操作日志' }}</span>
          </div>
        </template>

        <template v-slot:loading>
          <q-inner-loading showing color="primary">
            <q-spinner-dots size="50px" />
          </q-inner-loading>
        </template>

        <template v-slot:body-cell-report="props">
          <q-td :props="props">
            <q-btn
              v-if="props.row.report_url"
              color="primary"
              label="下载"
              padding="4px 8px"
              @click="downloadReport(props.row)"
            />
            <span v-else>-</span>
          </q-td>
        </template>
      </q-table>

      <div class="row justify-center q-mt-md">
        <q-pagination
          v-model="pagination.page"
          color="grey-8"
          :max="pagesNumber"
          size="sm"
          :max-pages="6"
          boundary-numbers
          @update:model-value="onPageChange"
        />
      </div>
    </q-page>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, computed } from 'vue'
import { useQuasar } from 'quasar'
import { getOperationLogs, downloadOperationReport } from 'src/api/operation'

const columns = [
  {
    name: 'created_at',
    align: 'center',
    label: '操作时间',
    field: row => row.created_at,
    sortable: true
  },
  {
    name: 'username',
    align: 'center',
    label: '操作人',
    field: row => row.username
  },
  {
    name: 'operation_type',
    align: 'center',
    label: '操作类型',
    field: row => {
      const option = operationOptions.find(opt => opt.value === row.operation_type)
      return option ? option.label : row.operation_type
    }
  },
  {
    name: 'filename',
    align: 'center',
    label: '文件名称',
    field: row => row.filename
  },
  {
    name: 'status',
    align: 'center',
    label: '操作状态',
    field: row => row.status === 1 ? '成功' : '检查未通过'
  },
  {
    name: 'report',
    align: 'center',
    label: '操作报告',
  },
  {
    name: 'description',
    align: 'center',
    label: '描述',
    field: row => row.description
  }
]

const $q = useQuasar()
const loading = ref(false)
const dataList = ref([])
const pagination = reactive({
  sortBy: 'created_at',
  descending: true,
  page: 1,
  rowsPerPage: 10,
  rowsNumber: 0
})

const searchForm = reactive({
  username: '',
  filename: '',
  operation_type: null
})

const operationOptions = [
  { label: '文件检查', value: 'check_excel' },
  { label: '数据导入', value: 'import_excel' }
]

const pagesNumber = computed(() => Math.ceil(pagination.rowsNumber / pagination.rowsPerPage))

const loadData = async () => {
  loading.value = true
  try {
    // 这里替换为实际的 API 调用
    const response = await getOperationLogs({
      page: pagination.page,
      pageSize: pagination.rowsPerPage,
      ...searchForm
    })

    dataList.value = response.data.items
    pagination.rowsNumber = response.data.total
  } catch (error) {
    console.error('加载数据失败:', error)
    $q.notify({
      type: 'negative',
      message: '加载数据失败，请稍后重试'
    })
  } finally {
    loading.value = false
  }
}

const resetSearch = () => {
  searchForm.username = ''
  searchForm.filename = ''
  searchForm.operation_type = null
  loadData()
}

const downloadReport = async (row) => {
  if (!row.report_url) return

  try {
    const response = await downloadOperationReport(row.report_url)
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `操作报告_${row.filename}`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('下载报告失败:', error)
    $q.notify({
      type: 'negative',
      message: '下载报告失败，请稍后重试'
    })
  }
}

const onPageChange = () => {
  loadData()
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss">
.page-header {
  z-index: 2;
  margin: 8px;
  .header-title {
    font-size: 14px;
    .first-breadcrumbs {
      .q-breadcrumbs__el-icon {
        font-size: 120%;
        position: relative;
        top: -1px;
      }
    }
  }
}
</style>
